using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class TJSDK:TJSingleton<TJSDK>
{
	/// 友盟、TalkingData统计(不含渠道统计)
	private TJAnalyze analyze;

	/// 友盟分享(Android版)
	private UMShareAndroid share;

	/// 渠道支付
	private PayBase pay;

	/// 地区屏蔽
	private AdLocation adLocation;

	/// 唤醒提示
	private AwakeAds awakeHint;

	/// 渠道广告
	private List<AdsBase> adsList = new List<AdsBase> ();
	private List<int> insertReadyList = new List<int> ();
	private List<int> incentReadyList = new List<int> ();
	private List<int> splashReadyList = new List<int> ();
	private int curBannerIndex = -1;
	private int curInsertIndex = -1;
	private int curIncentIndex = -1;
	private int curVideoIndex = -1;
	private int curNativeIndex = -1;
	private int curSplashIndex = -1;

	private int turnBannerIndex = -1;
	private int turnInsertIndex = -1;
	private int turnIncentIndex = -1;
	private int turnVideoIndex = -1;
	private int turnNativeIndex = -1;
	private int turnSplashIndex = -1;

	void Start ()
	{
		Init ();
	}

	#region 初始化

	/// 初始化
	private void Init ()
	{
		try{
			ShowSDKData();
		} catch (Exception e) {
			TJLogError ("打印数据错误:" + e.Message);
		}
		try {
			InitAnalyze ();
		} catch (Exception e) {
			TJLogError ("统计初始化错误:" + e.Message);
		}
		try {
			InitShare ();
		} catch (Exception e) {
			TJLogError ("分享初始化错误:" + e.Message);
		}
		try {
			InitAds ();
		} catch (Exception e) {
			TJLogError ("广告初始化错误:" + e.Message);
		}
		try {
			InitPay ();
		} catch (Exception e) {
			TJLogError ("支付初始化错误:" + e.Message);
		}

		try {
			InitAdLocation ();
		} catch (Exception e) {
			TJLogError ("地区屏蔽初始化错误:" + e.Message);
		}

		try {
			InitAwake ();
		} catch (Exception e) {
			TJLogError ("唤醒初始化错误:" + e.Message);
		}
	}

	/// 打印SDK数据
	private void ShowSDKData(){
		System.Reflection.FieldInfo[] fieldInfos = typeof(SDKData).GetFields();

		string infoStr = "\n#################### 以下是SDK信息 ####################\n";
		foreach (System.Reflection.FieldInfo info in fieldInfos)
		{
			infoStr += (string.Format ("### {0}: {1}\n", 
				DataType.GetDataTypeName(info.Name), 
				typeof(SDKData).GetField(info.Name).GetValue(null)));
		}
		infoStr += "#################### 以上是SDK信息 ####################\n";
		TJLog (infoStr);
	}

	/// 获取SDK数据属性值
	private string GetSDKDataValue(string valueName){
		string value = null;
		if (typeof(SDKData).GetField (valueName) != null) {
			value = typeof(SDKData).GetField (valueName).GetValue (null).ToString();
		}
		return value;
	}

	/// 初始化统计
	private void InitAnalyze ()
	{
		analyze = new TJAnalyze ();
		analyze.Init (SDKData.ChannelId, SDKData.UMENG_APPKEY, SDKData.TalkingDataKey);
		TJLog ("初始化统计完成");

		AnalyzaBase channelAnalyza = null;
		#if baidu
		channelAnalyza = new AnalyzeBaidu();
		channelAnalyza.Init ();
		#endif

		#if meizu
		channelAnalyza = new AnalyzeMeizu();
		channelAnalyza.Init(SDKData.MeizuAppId,SDKData.MeizuAppKey);
		#endif
	}

	/// 初始化分享
	private void InitShare ()
	{
		#if UNITY_ANDROID
		share = new UMShareAndroid();
		share.Init (
			SDKData.WeixinKey,SDKData.WeixinSecret, 
			SDKData.QqKey, SDKData.QqSecret, 
			SDKData.SinaKey, SDKData.SinaSecret
		);
		#elif UNITY_IOS
		UmengShare.InitUmengKey (
			SDKData.QqKey, SDKData.QqSecret, 
			SDKData.WeixinKey,SDKData.WeixinSecret, 
			SDKData.SinaKey, SDKData.SinaSecret
		);
		#endif
		TJLog ("初始化分享完成");
	}

	/// 初始化广告
	private void InitAds ()
	{

		adsList.Clear ();

		#if gdt
		AdsBase gdtAds = new GdtAds ();

		string GdtAppId,GdtBannerKey,GdtInsertKey,GdtIncentInsertKey,GdtNativeKey,GdtIncentSplashKey;
		GdtAppId = GetSDKDataValue("GdtAppId");
		GdtBannerKey = GetSDKDataValue("GdtBannerKey");
		GdtInsertKey = GetSDKDataValue("GdtInsertKey");
		GdtIncentInsertKey = GetSDKDataValue("GdtIncentInsertKey");
		GdtNativeKey = GetSDKDataValue("GdtNativeKey");
		GdtIncentSplashKey = GetSDKDataValue("GdtIncentSplashKey");

		gdtAds.Init (SDKData.GdtAppId, SDKData.GdtBannerKey, SDKData.GdtInsertKey, SDKData.GdtIncentInsertKey,SDKData.GdtNativeKey,GdtIncentSplashKey);
		TJLog ("广点通 广告初始化完成");
		adsList.Add (gdtAds);
		#endif

		#if applovin
		AdsBase appAds = new ApplovinAds();
		appAds.Init (SDKData.Applovinkey, "TJSDK");
		TJLog ("Applovin 广告初始化完成");
		adsList.Add(appAds);
		#endif

		#if vungle
		AdsBase vunAds = new VungleAds();
		vunAds.Init (SDKData.VungleKey);
		TJLog ("Vungle 广告初始化完成");
		adsList.Add(vunAds);
		#endif

		#if oppo
		AdsBase oppoAds = new OppoAds();
		oppoAds.Init (SDKData.OppoAppId, SDKData.OppoBannerKey, SDKData.OppoInsertKey);
		TJLog ("Oppo 广告初始化完成");
		adsList.Add(oppoAds);
		#endif

		#if lenovo
		AdsBase lestoreAds = new LenovoAds();
		lestoreAds.Init (SDKData.LenovoBannerKey, SDKData.LenovoInsertKey, SDKData.LenovoIncentVideoKey);
		TJLog ("联想 广告初始化完成");
		adsList.Add(lestoreAds);
		#endif

		#if yumi
		AdsBase yumiAds = new YumiAds();
		yumiAds.Init(SDKData.YumiId);
		TJLog ("玉米 广告初始化完成");
		adsList.Add(yumiAds);
		#endif
	}

	/// 初始化支付
	private void InitPay ()
	{
		#if m4399
		pay = new M4399Pay();
		pay.Init (SDKData.M4399Key, SDKData.AppName, M4399Pay.Direction.portrait);
		TJLog ("4399 支付初始化完成");
		#endif

		#if oppo
		pay = new OppoPay ();
		pay.Init (SDKData.OppoAppSecret);
		TJLog ("Oppo 支付初始化完成");
		#endif

		#if vivo
		pay = new VivoPay ();
		pay.Init (SDKData.VivoAppId,SDKData.VivoCpId,SDKData.VivoAppKey);
		TJLog ("Vivo 支付初始化完成");
		#endif

		#if wiipay
		pay = new WiiPay ();
		pay.Init ();
		TJLog ("微派 支付初始化完成");
		#endif

		#if iappay
		pay = new IapPay();
		pay.Init (SDKData.IapPayAppId, SDKData.IapPayWaresId,SDKData.IapPayPublicKey, SDKData.IapPayPrivateKey,IapPay.Direction.portrait);
		TJLog ("爱贝 支付初始化完成");
		#endif
	}

	/// 初始化地区屏蔽
	private void InitAdLocation ()
	{
		if (typeof(SDKData).GetField ("TjAppKey") != null) {
			adLocation = new AdLocation ();
			adLocation.Init (typeof(SDKData).GetField ("TjAppKey").GetValue (null).ToString());
			TJLog ("地区屏蔽初始化完成");
		}
	}

	/// 初始化唤醒提示
	private void InitAwake ()
	{
		if (typeof(SDKData).GetField ("AwakeTime") != null) {
			awakeHint = new AwakeAds ();
			awakeHint.Init (typeof(SDKData).GetField ("AwakeTime").GetValue (null).ToString());
			TJLog ("唤醒提示初始化完成");
		}
	}

	#endregion

	#region 统计相关

	/// 统计事件
	public void AnalyzeEvent (string event_name)
	{
		TJLog ("统计事件:" + event_name);
		if (analyze == null) {
			return;
		}
		analyze.Events (event_name);
	}

	/// 统计事件开始
	public void AnalyzeEventBegin (string event_name)
	{
		TJLog ("统计事件开始:" + event_name);
		if (analyze == null) {
			return;
		}
		analyze.EventsBegin (event_name);
	}
	/// 统计事件结束
	public void AnalyzeEventEnd (string event_name)
	{
		TJLog ("统计事件结束:" + event_name);
		if (analyze == null) {
			return;
		}
		analyze.EventsEnd (event_name);
	}

	#endregion

	#region 广告相关
	/// 广告回调
	void OnADCallBack (string result)
	{
		TJLog ("广告回调:" + result);
		if (adsList.Count == 1) {
			adsList [0].OnADCallback (result);
		} else if (adsList.Count >= 2) {
			if (result.Contains (AdsBase.AdsTypes.banner)) {
				adsList [curBannerIndex].OnADCallback (result);
			} else if (result.Contains (AdsBase.AdsTypes.insert)) {
				adsList [curInsertIndex].OnADCallback (result);
			} else if (result.Contains (AdsBase.AdsTypes.incent)) {
				adsList [curIncentIndex].OnADCallback (result);
			} else if (result.Contains (AdsBase.AdsTypes.video)) {
				adsList [curVideoIndex].OnADCallback (result);
			} else if (result.Contains (AdsBase.AdsTypes.native)) {
				adsList [curNativeIndex].OnADCallback (result);
			}
		}
	}

	/// 展示开屏
	public void ShowSplash (Action<bool> act = null)
	{
		TJLog ("展示 开屏 广告");
		if (adsList.Count == 1) {
			adsList [0].ShowSplash (act);
		}
		if (adsList.Count >= 2) {
			for (int i = 0; i < adsList.Count; i++) {
				if (adsList [i] is GdtAds) {
					curSplashIndex = i;
					adsList [i].ShowSplash (act);
				}
			}
		}
	}

	/// 展示横幅
	public void ShowBanner (Action<bool> act = null)
	{
		TJLog ("展示 横幅 广告");
		if (adsList.Count == 1) {
			adsList [0].ShowBanner (act);
		}
		if (adsList.Count >= 2) {
			if (turnBannerIndex == -1) {
				turnBannerIndex = UnityEngine.Random.Range (0, adsList.Count);
			} else {
				turnBannerIndex++;
				if (turnBannerIndex >= adsList.Count) {
					turnBannerIndex = 0;
				}
			}
			if (curBannerIndex != -1 && turnBannerIndex != curBannerIndex) {
				adsList [curBannerIndex].CloseBanner();
			}
			curBannerIndex = turnBannerIndex;
			adsList [curBannerIndex].ShowBanner (act);
		}
	}

	/// 关闭横幅
	public void CloseBanner ()
	{
		TJLog ("关闭 横幅 广告");
		if (adsList.Count == 1) {
			adsList [0].CloseBanner ();
		}
		if (adsList.Count >= 2) {
			if (curBannerIndex >= 0) {
				adsList [curBannerIndex].CloseBanner ();
			}
		}
	}

	/// 插屏状态
	public bool IsInsertReady ()
	{
		TJLog ("判断 插屏 广告状态");
		if (adsList.Count == 1) {
			return adsList [0].IsInsertReady ();
		} else if (adsList.Count >= 2) {
			insertReadyList.Clear ();
			for (int i = 0; i < adsList.Count; i++) {
				if (adsList [i].IsInsertReady ()) {
					insertReadyList.Add (i);
				}
			}
			return insertReadyList.Count > 0;
		} else {
			return false;
		}
	}

	/// 展示插屏
	public void ShowInsert (Action<bool> act = null)
	{
		TJLog ("展示 插屏");
		if (adsList.Count == 1) {
			if (adsList [0].IsInsertReady ()) {
				adsList [0].ShowInsert (act);
			}
		} else if (adsList.Count >= 2) {
			if (IsInsertReady ()) {
				if (turnInsertIndex == -1) {
					turnInsertIndex = UnityEngine.Random.Range (0, insertReadyList.Count);
				} else {
					turnInsertIndex++;
					if (turnInsertIndex >= insertReadyList.Count) {
						turnInsertIndex = 0;
					}
				}
				curInsertIndex = turnInsertIndex;
				adsList [insertReadyList[curInsertIndex]].ShowInsert (act);
			} else {
				TJLogError ("无可用插屏");
			}
		}
	}

	/// 激励视频状态
	public bool IsIncentReady ()
	{
		TJLog ("判断 激励 视频广告状态");
		if (adsList.Count == 1) {
			return adsList [0].IsIncentReady ();
		} else if (adsList.Count >= 2) {
			incentReadyList.Clear ();
			for (int i = 0; i < adsList.Count; i++) {
				if (adsList [i].IsIncentReady ()) {
					incentReadyList.Add (i);
				}
			}
			return incentReadyList.Count > 0;
		} else {
			return false;
		}
	}

	/// 展示激励视频
	public void ShowIncentVideo (Action<bool> act = null)
	{
		TJLog ("展示 激励 视频");
		if (adsList.Count == 1) {
			if (adsList [0].IsIncentReady ()) {
				adsList [0].ShowIncent (act);
			}
		} else if (adsList.Count >= 2) {
			if (IsIncentReady ()) {
				if (turnIncentIndex == -1) {
					turnIncentIndex = UnityEngine.Random.Range (0, incentReadyList.Count);
				} else {
					turnIncentIndex++;
					if (turnIncentIndex >= incentReadyList.Count) {
						turnIncentIndex = 0;
					}
				}
				curIncentIndex = turnIncentIndex;
				adsList [incentReadyList[curIncentIndex]].ShowIncent (act);
			} else {
				TJLogError ("无可用激励视频");
			}
		}
	}

	/// 展示原生广告
	public void ShowNative (Action<bool> act = null)
	{
		TJLog ("展示 原生 广告");
		for (int i = 0; i < adsList.Count; i++) {
			if (adsList [i] is GdtAds) {
				curNativeIndex = i;
				adsList [i].ShowNative (act);
			}
		}
	}

	/// 关闭原生广告
	public void CloseNative ()
	{
		TJLog ("关闭 原生 广告");
		if (curNativeIndex >= 0) {
			adsList [curNativeIndex].CloseNative ();
		}
	}

	#endregion

	#region 支付相关

	/// Android支付
	/// moneyAmount: 支付金额
	/// productName: 显示在支付页面的商品名称
	/// payCallBack: 支付回调，回调方法含有索引参数
	public void PayAndroid (string moneyAmount, string productName,string productDesc, System.Action<bool> payCallBack)
	{
		TJLog ("Android 支付金额:" + moneyAmount + ",商品名称:" + productName + ",商品描述:" + productDesc);
		if (pay != null) {
			pay.Pay (moneyAmount, productName, productDesc, payCallBack);
		} else {
			TJLog ("支付未初始化");
		}
	}

	/// 苹果支付
	/// index: 苹果支付编码
	/// payCallBack: 支付回调，回调方法含有索引参数，是否成功 bool 量
	public void PayApple(int index, ApplePay.PayCallback payCallBack){
		TJLog ("苹果支付编码:" + index);
		ApplePay.Buy(index, payCallBack);
	}
	/// 苹果恢复购买
	/// index: 恢复购买支付编码
	/// payCallBack: 支付回调，回调方法含有索引参数，是否成功 bool 量
	public void RestoreApple(int index, ApplePay.PayCallback payCallBack){
		TJLog ("苹果恢复购买支付编码:" + index);
		ApplePay.Restore(index, payCallBack);
	}

	/// 支付回调接收
	void OnPayResult (string result)
	{
		TJLog ("支付回调:" + result);
		pay.OnPayResult (result);
	}

	#endregion

	#region 分享相关

	#if UNITY_ANDROID
	/// 分享(所有平台): content:分享内容, title:分享标题, imaPath:分享图片路径, url:分享地址, ac:分享回调 
	public void Share (string title, string content, string imaPath, string url, Action<bool> act = null)
	{
		share.Share (title, content, imaPath, url, act);
	}

	/// 分享(所有平台): title:分享标题, content:分享内容, imaPath:分享图片路径, url:分享地址, isSame:分享内容相同, ac:分享回调 
	public void Share (string title, string content, string imagePath, string url,bool isSame, Action<bool> act = null)
	{
		share.Share (title, content, imagePath, url, isSame, act);
	}

	/// 分享(指定平台): platform:分享平台, title:分享标题, content:分享内容, imaPath:分享图片路径, url:分享地址, ac:分享回调 
	public void Share (Platform platform, string title, string content, string imagePath, string url, Action<bool> act = null)
	{
		share.Share (platform, title, content, imagePath, url, act);
	}

	/// 设置分享(设置单个平台内容): platform:分享平台, title:分享标题, content:分享内容, imaPath:分享图片路径, url:分享地址
	public void SetShare (Platform platform, string title, string content, string imagePath, string url)
	{
		share.SetShare (platform, title, content, imagePath, url);
	}

	/// 分享回调结果
	void OnShareResult(string result){
		share.OnShareResult (result);
	}

	#elif UNITY_IOS
	/// 分享(所有平台): content:分享内容, imaPath:分享图片路径, title:分享标题, url:分享地址, act:分享回调 
	public void Share (string content, string imaPath, string title, string url, Action act = null)
	{
		UmengShare.OpenSharePlateform (content, imaPath, title, url, act);
	}
	/// 分享(指定平台): platform:分享平台, content:分享内容, imaPath:分享图片路径, title:分享标题, url:分享地址, act:分享回调 
	public void Share (Platform platform, string content, string imagePath, string title, string url, Action act = null)
	{
		UmengShare.DirectShare (platform, content, imagePath, title, url, act);
	}
	/// 分享(仅分享图片): imaPath:分享图片路径, act:分享回调 
	public void Share (string imaPath, Action act = null)
	{
		UmengShare.OpenShareImageOnly (imaPath, act);
	}

	#endif

	#region 地区屏蔽相关

	public AdLocation.AdLocState GetAdLocState(){
		if (adLocation != null) {
			return adLocation.GetAdLocState ();
		} else {
			return AdLocation.AdLocState.UnUse;
		}
	}

	/// 地区屏蔽回调结果
	void OnADLocCallBack(string result){
		adLocation.OnADLocCallBack (result);
	}

	#endregion

	#region 唤醒提示相关

	/// 唤醒提示时间
	public void SetAwakeTime(int time){
		awakeHint.SetTime (time);
	}

	/// 唤醒提示回调结果
	void OnAwakeResult(string result){
		awakeHint.OnAwakeResult (result);
	}
	#endregion

	#endregion

	#region 排行榜相关

	/// 提交排行榜分数
	public void CommitScore (int score)
	{
		#if UNITY_IOS
		GameCenterManager.ReportScore(SDKData.LeadBoardId,score);
		#endif
	}
	/// 展示排行榜面板
	public void ShowLeardBoard ()
	{
		GameCenterManager.ShowLeardBoard ();
	}

	#endregion

	#region 退出游戏

	/// 退出游戏
	public void QuitGame ()
	{
		TJLog ("退出游戏");
		#if oppo || vivo
		pay.OnExitGame ();
		#else
		Application.Quit ();
		#endif
	}

	#endregion
}